<template>
  <div class="box">
    <page-box v-if="!showPage">
      <template #top>
        <alert-msg
          content="IVR语音导航实现语音菜单的扁平化，如TTS语音提示，上下班时间判断，转人工或外线和语音信箱留言等。用户可根据企业自身业务需求配置不同客户来引导的场景"
        >
          <template #icon>
            <i class="MC_iconfont MC_icon-xinxi-mian"></i>
          </template>
        </alert-msg>
      </template>
      <template #search>
        <search-form :fieldList="fieldList" :form="query" @onSearchFun="onPageChange(1)"></search-form>
      </template>
      <template #btn>
        <el-button @click="onOpenImport">导入</el-button>
        <el-button @click="onPageChange">查询</el-button>
        <el-button type="primary" @click="onJump">新建</el-button>
      </template>
      <template #table>
        <resize-table
          :topHeight="48"
          :showPagination="true"
          @onPageChange="onPageChange"
          @onPageSizeChange="onPageSizeChange"
          :data="list"
          :pagingData="page"
          :headers="headers"
        >
          <template #updateUser="{ scope }">
            <span class="updateUser">
              {{ userObj && userObj[scope.row.updateUser] ? userObj[scope.row.updateUser].name : '--' }}
            </span>
          </template>
          <template #status="{ scope }">
            <el-switch
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              @change="(val: any) => onChangeStatus(val, scope.row)"
              :before-change="() => beforeChangeStatus(scope.row)"
              v-model="scope.row.status"
            ></el-switch>
          </template>
          <template #operation="{ scope }">
            <el-button-group>
              <el-button type="primary" link @click="onJump(scope.row)">编辑</el-button>
              <el-button type="primary" link @click="onOpenExport(scope.row)">导出</el-button>
              <el-button type="primary" link @click="onOpenDel(scope.row)">删除</el-button>
            </el-button-group>
          </template>
        </resize-table>
      </template>
    </page-box>
    <div v-else class="chart-box">
      <flow-chart
        v-if="!isEmpty(ivrData)"
        :ivrData="ivrData"
        @ivrSaveSuccess="ivrSaveSuccess"
        @pageBack="pageBack"
      ></flow-chart>
    </div>
  </div>
</template>
<script lang="ts">
import { Search } from '@element-plus/icons-vue'
import { onBeforeUnmount, onMounted, reactive, toRefs, defineComponent, computed, markRaw } from 'vue'
import resizeTable from '@/common/components/resize-table/index.vue'
import usePage from '@/common/utils/hooks/use-page'
import FlowChart from './flow-chart/index.vue'
import alertMsg from '@common/components/alert/index.vue'
import { addFileInput, download, readFile } from '../../utils/utils'
import { DISABLE, ENABLE_ZH, DISABLE_ZH } from '../../utils/constance'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ivrDelete, ivrImport, changeStatus } from '../../apis/ivr'
import ivr from '@app/call-center/store/modules/ivr'
import PageBox from '@/common/components/page-box.vue'
import mcGetCache from '@/common/utils/mc-get-cache'
import { commonStore } from '@/common/store/modules/common'
import { isEmpty } from 'lodash'
import localforage from 'localforage'
import { NODE_STORE } from './constants'
import searchForm from '@/common/components/base-form/form.vue'
import deleteIcon from '@/common/components/delete-icon/index.vue'
import { newDate } from '@/common/utils/common'
const ivrModule = ivr()
interface State {
  input: HTMLInputElement | null
  query: Record<string, unknown>
  headers: Record<string, unknown>[]
  showPage: boolean
  fileList: any[]
  ivrData: any
  fieldList: any
}
export default defineComponent({
  name: 'voice-nav',
  components: { FlowChart, resizeTable, PageBox, alertMsg, searchForm },
  setup() {
    const state: State = reactive({
      fileList: [],
      fieldList: [
        {
          name: '语音导航',
          field: 'name',
          type: 'text',
          placeholder: '导航名称/导航编号'
        },
        {
          name: '状态',
          field: 'status',
          type: 'dropdown',
          choices: [
            { value: '', label: '全部' },
            { value: 0, label: '停用' },
            { value: 1, label: '启用' }
          ]
        }
      ],
      ivrData: {},
      input: null,
      query: {
        name: '',
        status: ''
      },
      headers: [
        {
          label: '名称',
          fixed: true,
          show: true,
          prop: 'name'
        },
        {
          label: '编号',
          show: true,
          prop: 'id'
        },
        {
          label: '服务号',
          show: true,
          prop: 'numbers'
        },
        {
          label: '备注',
          show: true,
          prop: 'remark'
        },
        {
          label: '更新时间',
          show: true,
          prop: 'updateTime',
          sortable: true,
          width: 200
        },
        {
          label: '更新人',
          show: true,
          prop: 'updateUser',
          custom: true
        },
        {
          label: '状态',
          show: true,
          prop: 'status',
          custom: true
        },
        {
          label: '操作',
          show: true,
          prop: 'operation',
          disenable: true,
          width: 150,
          custom: true
        }
      ],
      showPage: false
    })

    const { list, page, onPageChange, onPageSizeChange } = usePage({
      url: '/call/web/call/action/config/ivr/query',
      reqParams: state.query,
      method: 'GET',
      pageReqKeys: {
        'page-size': 'pageSize',
        'current-page': 'pageNumber',
        total: 'total',
        'page-sizes': 'page-sizes'
      },
      pageResKeys: {
        list: 'data.list',
        total: 'data.page.total'
      }
    })

    onMounted(async () => {
      onPageChange()
      state.input = addFileInput()
      state.input.addEventListener('change', onImport)
    })

    onBeforeUnmount(() => {
      state.input?.removeEventListener('change', onImport)
    })

    const onOpenImport = () => {
      state.input?.click()
    }
    // 获取所有员工的map信息
    const userObj: any = computed(() => {
      // 员工
      return commonStore().publicCache.userCacheObj || {}
    })

    const onImport = async (e: any) => {
      const json = await readFile(e)
      await ivrImport(json).then(() => ElMessage.success('导入成功'))
      onPageChange()
    }

    const beforeChangeStatus = (row: any) =>
      ElMessageBox.confirm(`确定要${row.status === DISABLE ? ENABLE_ZH : DISABLE_ZH}【${row.name}】吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

    const onChangeStatus = async (val: any, row: any) => {
      if (!row.id) {
        return
      }
      await changeStatus({
        id: row.id,
        status: val
      }).then(() => {
        mcGetCache.$updateCacheBySingleKey('ivrNav', { id: row.id, key: 'status', value: val }, 'id', 'hasObj')
        ElMessage.success('操作成功')
      })
      onPageChange()
    }

    const onExport = (data: any) => {
      const ivrData: Record<string, unknown> = {}
      ivrData.lineList = data.lineList
      ivrData.name = newDate().getTime() + ''
      ivrData.nodeList = data.nodeList
      ivrData.remark = data.remark
      const url = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(ivrData, null, '\t'))
      download({
        downloadName: data.name + '.json',
        url
      })
    }

    const onOpenExport = (row: any) => {
      ElMessageBox.confirm('确定要导出该语音导航数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => onExport(row))
        .catch()
    }

    const onDel = async (row: any) => {
      await ivrDelete(row).then(() => ElMessage.success('删除成功'))
      onPageChange()
    }
    const onOpenDel = (row: any) => {
      ElMessageBox.confirm('确定要删除该语音导航数据吗？', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        icon: markRaw(deleteIcon)
      })
        .then(() => onDel(row))
        .catch()
    }

    const onJump = async (row: any) => {
      state.ivrData = row
      localforage.setItem(NODE_STORE, row)
      ivrModule.toggleNav(true)
      ivrModule.setIvrData(row)
      state.showPage = true
    }

    const ivrSaveSuccess = (): void => {
      state.showPage = false
      onPageChange(1)
    }

    const pageBack = (): void => {
      ElMessageBox.confirm('您没有进行保存操作, 确定离开页面吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        state.showPage = false
      })
    }
    return {
      ...toRefs(state),
      pageBack,
      ivrSaveSuccess,
      onJump,
      onOpenDel,
      onOpenExport,
      onChangeStatus,
      beforeChangeStatus,
      onOpenImport,
      list,
      page,
      onPageChange,
      onPageSizeChange,
      isEmpty,
      Search,
      userObj
      // ivrData: ivrModule.ivrData
    }
  }
})
</script>

<style lang="stylus" scoped>
.box
  position: relative;
  height 93vh
.chart-box
  height 100%
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  background: #fff;
.left-space
  margin-left 20px
.updateUser
  white-space nowrap
</style>
